package weaver.jobs.cyjt.duss.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author dusongsong
 * @date 2024年10月08日 10:02
 */
public class MchrUtil extends BaseBean {

    private final String baseurl = getPropValue("mchr", "url");
    private final String appKey = getPropValue("mchr", "appKey");
    private final String appSecret = getPropValue("mchr", "appSecret");

    /**
     * 发起请求
     *
     * @param apiurl  请求的URL
     * @param timeout 超时时间（秒）
     * @return 返回结果
     */
    private JSONObject sendOKHttpRequest(String apiurl, int timeout) {
        JSONObject resultJson = new JSONObject();
        String data = "";
        String message = "";

        // 创建OkHttpClient并设置超时时间
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(timeout, TimeUnit.SECONDS)
                .readTimeout(timeout, TimeUnit.SECONDS)
                .writeTimeout(timeout, TimeUnit.SECONDS)
                .build();

        // 设置请求体
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "");

        try {
            // 构建请求
            Request request = new Request.Builder()
                    .url(apiurl)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();

            // 执行请求
            try (Response response = client.newCall(request).execute()) {
                String result = Util.null2String(response.body().string());
                if (!"".equals(result)) {
                    data = result;
                    message = "success";
                } else {
                    message = "response result is null";
                }
            }
        } catch (IOException e) {
            message = "network error: " + e.getMessage();
            e.printStackTrace();
        } catch (Exception e) {
            message = "unexpected error: " + e.getMessage();
            e.printStackTrace();
        }

        resultJson.put("data", data);
        resultJson.put("message", message);
        return resultJson;
    }

    public String getFlowCreateURLList() {
        String apiurl = baseurl + "/mchr/api/services/flowCreateURLList";
        String token = getAppToken();
        writeLog(">>>>>getFlowCreateURLList>>>>token=" + token);
        if (!"".equals(token)) {
            apiurl += "?apptoken=" + token;
            JSONObject resultJson = sendOKHttpRequest(apiurl, 60);
            String message = Util.null2String(resultJson.getString("message"));
            if ("success".equals(message)) {
                return Util.null2String(resultJson.getString("data"));
            } else {
                writeLog(">>>>>getAppToken>>>>" + message);
            }
        }
        return "";
    }

    public String isExistFlowData() {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select group_concat(outkey) from uf_mchrlcpzb");
        rs.next();
        return Util.null2String(rs.getString(1));
    }

    private String getAppToken() {
        String apiurl = baseurl + "/mchr/api/oauth/apptoken";
        apiurl += "?appkey=" + appKey + "&appsecret=" + appSecret;
        JSONObject resultJson = sendOKHttpRequest(apiurl, 60);
        String message = Util.null2String(resultJson.getString("message"));
        if ("success".equals(message)) {
            JSONObject resultJsonData = JSONObject.parseObject(resultJson.getString("data"));
            return Util.null2String(resultJsonData.getString("token"));
        } else {
            writeLog(">>>>>getAppToken>>>>" + message);
        }
        return "";
    }

    /**
     * @Description: 建模权限重构
     */
    private void newModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight(true);
        modeRightInfo.editModeDataShare(userid, formmodeid, id);
    }

    /**
     * 将数据插入表单建模
     *
     * @param tablename
     * @param map
     * @return
     */
    public int insertModelData(String tablename, Map<String, Object> map) {
        int dataid = 0;
        RecordSet rs = new RecordSet();
        try {
            //查询该模块表名
            String uuid = UUID.randomUUID().toString();
            int formmodeid = getFormmodeid(tablename);
            String insSql = "insert into " + tablename
                    + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values(?,?,?,?,?)";
            Object[] params = {uuid, 1, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString(), formmodeid};
            if (rs.executeUpdate(insSql, params)) {
                dataid = ModeUUID2DataId(tablename, uuid);
                if (dataid > 0) {
                    //遍历数据 进行update
                    String updatesql = "update " + tablename + " set ";
                    Set<String> keySet = map.keySet();
                    for (String key : keySet) {
                        updatesql += key + "='" + map.get(key).toString() + "',";
                    }
                    if (updatesql.endsWith(",")) {
                        updatesql = updatesql.substring(0, updatesql.length() - 1);
                        updatesql += " where id=" + dataid;
                        boolean updateStat = rs.executeUpdate(updatesql);
                        writeLog(">>>>>insertModelData>>>>updatesql=" + updatesql);
                        if (!updateStat) {
                            dataid = 0;
                        }
                    }
                    //进行权限重构
                    newModeRight(1, formmodeid, dataid);
                }
            }
        } catch (Exception e) {
            writeLog(">>>>>insertModelData>>>>" + e.getMessage());
        }

        return dataid;
    }

    /**
     * 更新数据
     *
     * @param tablename 表名
     * @param map       数据集合
     * @param dataid    更新用唯一标识
     * @return
     */
    public boolean updateModelData(String tablename, String dataid, Map<String, Object> map) {
        RecordSet rs = new RecordSet();
        String updatesql = "update " + tablename + " set  ";
        String valuesStr = "";
        boolean flag = false;
        try {
            Set<String> keySet = map.keySet();
            for (String key : keySet) {
                String value = Util.null2String(map.get(key).toString());
                if (valuesStr.equals("")) {
                    valuesStr = key + "='" + value + "'";
                } else {
                    valuesStr += "," + key + "='" + value + "'";
                }
            }
            updatesql += valuesStr + " where outkey='" + dataid + "'";
            writeLog(">>>>>updateModelData>>>>updatesql=" + updatesql);
            flag = rs.execute(updatesql);
        } catch (Exception e) {
            writeLog(">>>>>updateModelData>>>>" + e.getMessage());
        }

        return flag;
    }

    /**
     * @Description: 根据建模表名和UUID获取数据ID 常用于建模的权限重构获取数据ID
     */
    private int ModeUUID2DataId(String tablename, String uuid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from " + tablename + " where modeuuid =?", uuid);
        rs.next();
        return Util.getIntValue(rs.getString(1));
    }

    /**
     * @Description: 获取建模Id
     */
    private int getFormmodeid(String tablename) {
        RecordSet rs = new RecordSet();
        String sql = "select m.id from modeinfo m left join WORKFLOW_BILL b on m.formid = b.id where b.tablename = ?";
        rs.executeQuery(sql, tablename);
        rs.next();
        return Util.getIntValue(rs.getString("id"));
    }

    /**
     *@Description: 判断是否是json数组格式
     */
    public boolean isJSONArray(String fieldvalue) {
        boolean flag = false;
        if (!(fieldvalue.trim().equals(""))) {
            try {
                JSONArray.parseArray(fieldvalue);
                flag = true;
            } catch (Exception e) {
                flag = false;
            }
        }
        return flag;
    }

    public static void main(String[] args) {
        String str = "9";
        List<String> list= Arrays.asList(str.split(","));
        System.out.println("arr="+list.contains("97"));
    }
}
